import 'package:flutter/material.dart';
import 'progress_toast.dart';

/// 进度任务演示页面
class ProgressTaskDemoPage extends StatefulWidget {
  const ProgressTaskDemoPage({super.key});

  @override
  State<ProgressTaskDemoPage> createState() => _ProgressTaskDemoPageState();
}

class _ProgressTaskDemoPageState extends State<ProgressTaskDemoPage> {
  bool _isTaskRunning = false;

  // 模拟不同的任务场景
  final List<Map<String, dynamic>> _taskScenarios = [
    {
      'name': '文件上传任务',
      'steps': [
        '准备上传文件',
        '压缩文件数据',
        '建立网络连接',
        '上传文件块 1/3',
        '上传文件块 2/3',
        '上传文件块 3/3',
        '验证文件完整性',
        '更新文件索引',
        '清理临时文件',
        '上传完成'
      ],
      'icon': Icons.cloud_upload_rounded,
      'color': Colors.blue,
    },
    {
      'name': '数据同步任务',
      'steps': [
        '检查网络连接',
        '获取服务器时间戳',
        '比较本地数据',
        '下载差异数据',
        '验证数据完整性',
        '更新本地数据库',
        '清理过期缓存',
        '同步完成'
      ],
      'icon': Icons.sync_rounded,
      'color': Colors.green,
    },
    {
      'name': '应用安装任务',
      'steps': [
        '下载安装包',
        '验证数字签名',
        '检查系统兼容性',
        '创建安装目录',
        '解压安装文件',
        '注册系统服务',
        '配置应用权限',
        '创建快捷方式',
        '清理安装临时文件',
        '安装完成'
      ],
      'icon': Icons.download_rounded,
      'color': Colors.orange,
    },
    {
      'name': '数据备份任务',
      'steps': [
        '扫描数据文件',
        '计算文件校验和',
        '压缩数据包',
        '加密敏感数据',
        '上传到云端',
        '验证备份完整性',
        '更新备份索引',
        '备份完成'
      ],
      'icon': Icons.backup_rounded,
      'color': Colors.purple,
    },
    {
      'name': '系统更新任务',
      'steps': [
        '检查更新版本',
        '下载更新包',
        '验证更新文件',
        '备份当前版本',
        '停止相关服务',
        '应用系统更新',
        '重启相关服务',
        '验证更新结果',
        '清理旧版本文件',
        '更新完成'
      ],
      'icon': Icons.system_update_rounded,
      'color': Colors.red,
    },
  ];

  /// 执行模拟任务
  Future<void> _executeTask(Map<String, dynamic> scenario) async {
    if (_isTaskRunning) return;

    setState(() {
      _isTaskRunning = true;
    });

    final steps = scenario['steps'] as List<String>;
    
    // 启动进度任务
    ProgressToastUtils.startProgressTask(
      context,
      taskName: scenario['name'],
      steps: steps,
      onCancel: () {
        setState(() {
          _isTaskRunning = false;
        });
      },
    );

    try {
      // 模拟执行各个步骤
      for (int i = 0; i < steps.length; i++) {
        if (!_isTaskRunning) break; // 检查是否被取消
        
        // 更新进度
        ProgressToastUtils.updateProgress(
          currentStep: i + 1,
          stepDescription: steps[i],
          additionalInfo: _getAdditionalInfo(scenario['name'], i + 1, steps.length),
        );

        // 模拟每个步骤的耗时（根据步骤类型调整）
        await Future.delayed(_getStepDuration(steps[i]));
      }

      if (_isTaskRunning) {
        // 任务成功完成
        ProgressToastUtils.completeTask(
          context,
          completionMessage: '${scenario['name']} 已成功完成！',
        );
      }
    } catch (e) {
      // 任务失败
      ProgressToastUtils.failTask(
        context,
        errorMessage: '${scenario['name']} 执行失败',
        onRetry: () => _executeTask(scenario),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isTaskRunning = false;
        });
      }
    }
  }

  /// 根据步骤获取附加信息
  String _getAdditionalInfo(String taskName, int currentStep, int totalSteps) {
    final random = DateTime.now().millisecond;
    
    if (taskName.contains('上传')) {
      final speed = (random % 50 + 10);
      return '传输速度: ${speed}MB/s';
    } else if (taskName.contains('下载')) {
      final size = (random % 500 + 100);
      return '已处理: ${size}MB';
    } else if (taskName.contains('同步')) {
      final items = (random % 1000 + 100);
      return '已同步: $items 项目';
    } else if (taskName.contains('备份')) {
      final files = (random % 5000 + 1000);
      return '已备份: $files 个文件';
    } else {
      final eta = ((totalSteps - currentStep) * 2);
      return '预计剩余: ${eta}s';
    }
  }

  /// 根据步骤类型获取持续时间
  Duration _getStepDuration(String stepName) {
    if (stepName.contains('下载') || stepName.contains('上传')) {
      return const Duration(milliseconds: 2000); // 网络操作较慢
    } else if (stepName.contains('验证') || stepName.contains('检查')) {
      return const Duration(milliseconds: 1500); // 验证操作中等
    } else if (stepName.contains('清理') || stepName.contains('配置')) {
      return const Duration(milliseconds: 800); // 本地操作较快
    } else {
      return const Duration(milliseconds: 1200); // 默认时间
    }
  }

  /// 获取颜色的深色调
  Color _getColorShade(Color color) {
    if (color == Colors.blue) return Colors.blue.shade700;
    if (color == Colors.green) return Colors.green.shade700;
    if (color == Colors.orange) return Colors.orange.shade700;
    if (color == Colors.purple) return Colors.purple.shade700;
    if (color == Colors.red) return Colors.red.shade700;
    return color; // 默认返回原色
  }

  /// 模拟失败场景
  Future<void> _executeFailureScenario() async {
    setState(() {
      _isTaskRunning = true;
    });

    final steps = ['初始化连接', '验证权限', '开始传输', '传输失败'];
    
    ProgressToastUtils.startProgressTask(
      context,
      taskName: '网络传输任务',
      steps: steps,
      onCancel: () {
        setState(() {
          _isTaskRunning = false;
        });
      },
    );

    try {
      for (int i = 0; i < 3; i++) {
        if (!_isTaskRunning) break;
        
        ProgressToastUtils.updateProgress(
          currentStep: i + 1,
          stepDescription: steps[i],
          additionalInfo: '正在处理...',
        );
        
        await Future.delayed(const Duration(milliseconds: 1500));
      }

      if (_isTaskRunning) {
        // 模拟失败
        throw Exception('网络连接超时');
      }
    } catch (e) {
      ProgressToastUtils.failTask(
        context,
        errorMessage: '网络传输失败: ${e.toString().replaceAll('Exception: ', '')}',
        onRetry: () => _executeFailureScenario(),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isTaskRunning = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('进度任务演示'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    Text(
                      '🚀 分步骤进度任务演示',
                      style: Theme.of(context).textTheme.titleLarge?.copyWith(
                        color: Colors.deepPurple,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '在左上角优雅地显示任务进度和百分比',
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Colors.grey.shade600,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 16),
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.blue.shade50,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: Colors.blue.shade200),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '✨ 功能特点:',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: Colors.blue.shade700,
                            ),
                          ),
                          const SizedBox(height: 8),
                          Text(
                            '• 实时进度百分比显示\n'
                            '• 流畅的动画效果\n'
                            '• 分步骤详细信息\n'
                            '• 支持取消操作\n'
                            '• 失败重试机制\n'
                            '• 优雅的完成提示',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.blue.shade600,
                              height: 1.4,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            
            const SizedBox(height: 24),
            
            Text(
              '选择任务场景:',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
            
            const SizedBox(height: 16),
            
            Expanded(
              child: GridView.builder(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 1.2,
                  crossAxisSpacing: 12,
                  mainAxisSpacing: 12,
                ),
                itemCount: _taskScenarios.length,
                itemBuilder: (context, index) {
                  final scenario = _taskScenarios[index];
                  return _buildTaskCard(scenario);
                },
              ),
            ),
            
            const SizedBox(height: 16),
            
            // 失败场景按钮
            ElevatedButton.icon(
              onPressed: _isTaskRunning ? null : _executeFailureScenario,
              icon: const Icon(Icons.error_outline),
              label: const Text('测试失败场景'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red.shade100,
                foregroundColor: Colors.red.shade700,
                minimumSize: const Size(double.infinity, 48),
              ),
            ),
            
            const SizedBox(height: 8),
            
            // 清除按钮
            OutlinedButton.icon(
              onPressed: () {
                ProgressToastUtils.clearProgress();
                setState(() {
                  _isTaskRunning = false;
                });
              },
              icon: const Icon(Icons.clear_all),
              label: const Text('清除所有Toast'),
              style: OutlinedButton.styleFrom(
                minimumSize: const Size(double.infinity, 48),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTaskCard(Map<String, dynamic> scenario) {
    final color = scenario['color'] as Color;
    final icon = scenario['icon'] as IconData;
    final name = scenario['name'] as String;
    final steps = scenario['steps'] as List<String>;

    return Card(
      elevation: _isTaskRunning ? 1 : 4,
      child: InkWell(
        onTap: _isTaskRunning ? null : () => _executeTask(scenario),
        borderRadius: BorderRadius.circular(12),
        child: Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            gradient: _isTaskRunning 
              ? null 
              : LinearGradient(
                  colors: [
                    color.withOpacity(0.05),
                    color.withOpacity(0.1),
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 48,
                height: 48,
                decoration: BoxDecoration(
                  color: _isTaskRunning 
                    ? Colors.grey.withOpacity(0.3)
                    : color.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(24),
                ),
                child: Icon(
                  icon,
                  color: _isTaskRunning ? Colors.grey : color,
                  size: 24,
                ),
              ),
              const SizedBox(height: 12),
              Text(
                name,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: _isTaskRunning ? Colors.grey : _getColorShade(color),
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 4),
              Text(
                '${steps.length} 个步骤',
                style: TextStyle(
                  fontSize: 12,
                  color: _isTaskRunning ? Colors.grey : Colors.grey.shade600,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
